<template>

  <div v-loading="loading" class="mch-form-main">

    <div class="instructions">
      <h3>说明</h3>
      <p>1、商户数据同步来源于享扫超管数据配置，该数据同步类型为不可编辑，同步的数据不支持修改，如果需要修改，请到享扫。</p>
      <p>2、资料修改仅支持签订权限组、服务期限（默认不限期）、商户标签选择，默认商户权限组为“基础权限组商户”，其他的商户logo、商户全名、商户简称、店铺数、后台账号、负责人、支付商户编号、手机号、邮箱、总部地址均不可修改。</p>
    </div>

    <el-form
      ref="form"
      :rules="rules"
      label-position="right"
      :model="form"
      size="small "
      label-width="150px"
    >
      <!--商户logo-->
      <el-form-item label="商户logo：" prop="logoUrl">
        <div class="flex-x-start-center">
          <el-upload
            class="upload-logo"
            :action="uploadImgApi"
            :show-file-list="false"
            :headers="{ 'X-SERVICER-TOKEN': $store.state.user.token }"
            :on-success="(res,file)=>{return uploadImgSuccess(res,file,'logoUrl')}"
            :before-upload="(file)=>{return uploadImgBefore(file,'logoUrl')}"
            :disabled="form_disabled"
          >
            <img v-if="form.logoUrl" :src="fileBaseUrl+form.logoUrl" class="img" alt>
            <i v-else class="el-icon-plus" />
          </el-upload>
          <el-button
            v-if="form.logoUrl"
            type="text"
            round
            size="small"
            class="app-color-danger"
            style="padding-left: 10px"
            :disabled="form_disabled"
            @click="form.logoUrl=null"
          >删除
          </el-button>
        </div>
        <ul class="app-tips">
          <li>1.仅支持JPG/PNG文件，且不超过500KB</li>
          <li>2.像素大小控制在300px * 300px以下</li>
        </ul>
      </el-form-item>
      <!--商户全称-->
      <el-form-item label="商户全称：" prop="fullName">
        <el-input v-model="form.fullName" maxlength="50" show-word-limit placeholder="请输入" :disabled="form_disabled" />
      </el-form-item>
      <!--商户简称-->
      <el-form-item label="商户简称：" prop="name">
        <el-input v-model="form.name" maxlength="12" show-word-limit placeholder="请输入" :disabled="form_disabled" />
      </el-form-item>
      <!--商户权限组-->
      <el-form-item label="商户权限组：" prop="businessPkg.packageId" :rules="rules.packageId">
        <el-radio-group v-model="form.businessPkg.packageId">
          <el-radio v-for="(item,index) in packageList" :key="index" :label="item.id">{{ item.name }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <!--服务期限-->
      <el-form-item label="服务期限：" class="no-margin is-required">
        <el-radio
          v-model="form.businessPkg.noExpired"
          :label="true"
        >不限期
        </el-radio>
        <el-radio
          v-model="form.businessPkg.noExpired"
          :label="false"

          style="margin-right: 10px"
        >有效期至
        </el-radio>
        <el-form-item
          class="inline-block"
          prop="businessPkg.invalidTime"
          :rules="rules.invalidTime"
        >
          <el-date-picker
            v-model="form.businessPkg.invalidTime"
            type="datetime"
            format="yyyy-MM-dd HH:mm"
            value-format="yyyy-MM-dd HH:mm"
            placeholder="选择到期时间"
            default-time="23:59:00"
            :disabled="form.businessPkg.noExpired"
            style="width:200px"
          />
        </el-form-item>

      </el-form-item>

      <el-form-item label="店铺数：" prop="businessPkg.maxShopNum" :rules="rules.maxShopNum">
        <el-input v-model="form.businessPkg.maxShopNum" maxlength="5" show-word-limit placeholder="请输入" :disabled="form_disabled" />
      </el-form-item>

      <!-- <el-form-item v-if="mode==='edit'" label="商户编号" prop="serial">
          <el-input disabled v-model="form.serial"/>
        </el-form-item>-->

      <el-form-item label="后台账号：" prop="userSuffix">
        <el-input v-if="mode==='add'" v-model="form.userSuffix" maxlength="20" show-word-limit placeholder="请输入" />
        <div v-else>{{ form.userSuffix }}</div>
      </el-form-item>

      <el-form-item label="负责人：" prop="principal">
        <el-input v-model="form.principal" maxlength="18" show-word-limit placeholder="请输入" :disabled="form_disabled" />
      </el-form-item>

      <el-form-item label="支付商户编号：" prop="mercNo">
        <el-input v-model="form.mercNo" maxlength="30" show-word-limit placeholder="请输入" :disabled="form_disabled" />
      </el-form-item>

      <el-form-item label="手机号：" prop="mobilePhone">
        <el-input v-model="form.mobilePhone" maxlength="11" show-word-limit placeholder="请输入" :disabled="form_disabled" />
      </el-form-item>

      <el-form-item label="邮箱：" prop="email">
        <el-input v-model="form.email" maxlength="60" show-word-limit placeholder="请输入" :disabled="form_disabled" />
      </el-form-item>

      <el-form-item label="总部地址：" prop="address">
        <el-input
          v-model.trim="form.address"
          :autosize="{ minRows: 2, maxRows: 5}"
          maxlength="50"
          show-word-limit
          type="textarea"
          placeholder="请输入"
          :disabled="form_disabled"
        />
      </el-form-item>

      <el-form-item label="商户标签：" prop="tags">
        <el-select
          v-model="form.tags"
          filterable
          multiple
          placeholder="请选择"
          clearable
        >
          <el-option
            v-for="v in tagOptions"
            :key="v"
            :label="v"
            :value="v"
          />
        </el-select>
      </el-form-item>

      <!-- 更多信息 -->

      <el-collapse-transition>
        <div v-show="isShowMoreConfig">

          <!-- 商户行业 -->
          <!--          <el-form-item label="商户行业：">-->
          <!--            <el-input placeholder="请输入" />-->
          <!--          </el-form-item>-->
          <!-- 营业执照号 -->
          <el-form-item label="营业执照号：">
            <el-input
              v-model="form.businessInfo.businessLicenseNum"
              maxlength="20"
              show-word-limit
              placeholder="请输入"
            />
          </el-form-item>
          <!-- 组织机构代码证号 -->
          <el-form-item label="组织机构代码证号：">
            <el-input
              v-model="form.businessInfo.organizationCode"
              maxlength="20"
              show-word-limit
              placeholder="请输入"
            />
          </el-form-item>
          <!-- 营业执照 -->
          <el-form-item>
            <div class="flex-x-start-center">
              <div style="margin-right:20px;">
                <div class="app-tips upload-card-tips">营业执照</div>
                <el-upload
                  class="upload-card"
                  :action="uploadImgApi"
                  :show-file-list="false"
                  :headers="{ 'X-SERVICER-TOKEN': $store.state.user.token }"
                  :on-success="(res,file)=>{return uploadImgSuccess(res,file,'businessLicenseImg')}"
                  :before-upload="(file)=>{return uploadImgBefore(file,'businessLicenseImg')}"
                >
                  <img
                    v-if="form.businessInfo.businessLicenseImg"
                    :src="fileBaseUrl+form.businessInfo.businessLicenseImg"
                    class="img"
                    alt
                  >
                  <i v-else class="el-icon-plus" />
                </el-upload>
                <div class="app-tips upload-card-tips">仅支持JPG/PNG文件，且不超过1MB</div>
                <div class="tc">
                  <el-button
                    v-if="form.businessInfo.businessLicenseImg"
                    type="text"
                    round
                    size="small"
                    class="app-color-danger "
                    style="padding-left: 10px"
                    @click="form.businessInfo.businessLicenseImg=null"
                  >删除
                  </el-button>
                </div>
              </div>
              <div>
                <div class="app-tips upload-card-tips">组织机构代码证</div>
                <el-upload
                  class="upload-card"
                  :action="uploadImgApi"
                  :show-file-list="false"
                  :headers="{ 'X-SERVICER-TOKEN': $store.state.user.token }"
                  :on-success="(res,file)=>{return uploadImgSuccess(res,file,'organizationCodeImg')}"
                  :before-upload="(file)=>{return uploadImgBefore(file,'organizationCodeImg')}"
                >
                  <img
                    v-if="form.businessInfo.organizationCodeImg"
                    :src="fileBaseUrl+form.businessInfo.organizationCodeImg"
                    class="img"
                    alt
                  >
                  <i v-else class="el-icon-plus" />
                </el-upload>
                <div class="app-tips upload-card-tips">仅支持JPG/PNG文件，且不超过1MB</div>
                <div class="tc">
                  <el-button
                    v-if="form.businessInfo.organizationCodeImg"
                    type="text"
                    round
                    size="small"
                    class="app-color-danger "
                    style="padding-left: 10px"
                    @click="form.businessInfo.organizationCodeImg=null"
                  >删除
                  </el-button>
                </div>
              </div>
            </div>
          </el-form-item>
          <!-- 法人姓名 -->
          <el-form-item label="法人姓名：" prop="businessInfo.legalPerson" :rules="rules.legalPerson">
            <el-input v-model="form.businessInfo.legalPerson" maxlength="18" show-word-limit placeholder="请输入姓名" />
          </el-form-item>
          <!-- 法人手机 -->
          <el-form-item
            label="法人手机："
            prop="businessInfo.legalMobilePhone"
            :rules="rules.legalMobilePhone"
          >
            <el-input
              v-model="form.businessInfo.legalMobilePhone"
              maxlength="11"
              show-word-limit
              placeholder="请输入"
            />
          </el-form-item>
          <!-- 身份证 -->
          <el-form-item
            label="法人身份证："
            prop="businessInfo.legalIdentityCard"
            :rules="rules.legalIdentityCard"
          >
            <el-input
              v-model="form.businessInfo.legalIdentityCard"
              maxlength="18"
              show-word-limit
              placeholder="请输入"
            />
          </el-form-item>
          <!-- 身份证 -->
          <el-form-item>
            <div class="flex-x-start-center">
              <div style="margin-right:20px;">
                <div class="app-tips upload-card-tips">身份证正面</div>
                <el-upload
                  class="upload-card"
                  :action="uploadImgApi"
                  :show-file-list="false"
                  :headers="{ 'X-SERVICER-TOKEN': $store.state.user.token }"
                  :on-success="(res,file)=>{return uploadImgSuccess(res,file,'legalIdentityCardImg')}"
                  :before-upload="(file)=>{return uploadImgBefore(file,'legalIdentityCardImg')}"
                >
                  <img
                    v-if="form.businessInfo.legalIdentityCardImg"
                    :src="fileBaseUrl+form.businessInfo.legalIdentityCardImg"
                    class="img"
                    alt
                  >
                  <i v-else class="el-icon-plus" />
                </el-upload>
                <div class="app-tips upload-card-tips">仅支持JPG/PNG文件，且不超过1MB</div>
                <div class="tc">
                  <el-button
                    v-if="form.businessInfo.legalIdentityCardImg"
                    type="text"
                    round
                    size="small"
                    class="app-color-danger "
                    style="padding-left: 10px"
                    @click="form.businessInfo.legalIdentityCardImg=null"
                  >删除
                  </el-button>
                </div>
              </div>

              <div>
                <div class="app-tips upload-card-tips">身份证背面</div>
                <el-upload
                  class="upload-card"
                  :action="uploadImgApi"
                  :show-file-list="false"
                  :headers="{ 'X-SERVICER-TOKEN': $store.state.user.token }"
                  :on-success="(res,file)=>{return uploadImgSuccess(res,file,'legalIdentityCardImg2')}"
                  :before-upload="(file)=>{return uploadImgBefore(file,'legalIdentityCardImg2')}"
                >
                  <img
                    v-if="form.businessInfo.legalIdentityCardImg2"
                    :src="fileBaseUrl+form.businessInfo.legalIdentityCardImg2"
                    class="img"
                    alt
                  >
                  <i v-else class="el-icon-plus" />
                </el-upload>
                <div class="app-tips upload-card-tips">仅支持JPG/PNG文件，且不超过1MB</div>
                <div class="tc">
                  <el-button
                    v-if="form.businessInfo.legalIdentityCardImg2"
                    type="text"
                    round
                    size="small"
                    class="app-color-danger "
                    style="padding-left: 10px"
                    @click="form.businessInfo.legalIdentityCardImg2=null"
                  >删除
                  </el-button>
                </div>
              </div>
            </div>
          </el-form-item>
        </div>
      </el-collapse-transition>

      <el-form-item>
        <el-button type="primary" round @click="submitForm">提交{{ mode === 'add' ? '添加' : '更新' }}</el-button>
        <el-button type="text" round @click="isShowMoreConfig=!isShowMoreConfig">{{
          isShowMoreConfig ? '隐藏' : '展开'
        }}高级配置
        </el-button>
      </el-form-item>
    </el-form>

    <el-dialog
      title="商户管理员信息"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="600px"
      @close="handleCloseDialog"
    >
      <el-form v-if="addMchInitData" size="small" label-position="right" label-width="120px">
        <el-form-item label="管理员账号：">
          {{ addMchInitData.username }}
        </el-form-item>
        <el-form-item label="初始密码：">
          {{ addMchInitData.initPassword }}
        </el-form-item>
        <el-form-item>
          <el-button
            type="text"
            @click="handleCopyClipboard(`管理员账号：${addMchInitData.username}  初始密码：${addMchInitData.initPassword}`,$event)"
          >
            复制到剪切板
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>

import validateMchForm from './mixin/validateMchForm'
import clip from '@/utils/clipboard'
import { mapGetters } from 'vuex'
import { addMch, updateMch, mchDetail } from '@/api/mch/index'
import { mchPackagePage } from '@/api/mch/package'
import { tagList } from '@/api/sp/tag'
import { uploadImgApi } from '@/api/upload'

export default {
  mixins: [validateMchForm],
  props: {
    tabName: {
      type: String,
      default: 'mchForm'
    }
  },
  data() {
    return {
      // 配置
      uploadImgApi: uploadImgApi,
      // 状态
      loading: false,
      isShowMoreConfig: false,
      dialogVisible: false,
      // 数据
      mode: 'add',
      businessId: null,
      packageList: [],
      tagOptions: [],
      addMchInitData: null,
      form: {
        logoUrl: 'business/logo/kun_store.jpg', // logo
        fullName: '', // 全称
        name: '', // 简称
        shopNum: '', // 店铺数
        userSuffix: '', // 后台账号
        principal: '', // 负责人
        mercNo: '', // 支付商户编号
        mobilePhone: '', // 负责人手机号
        email: '', //  负责人邮箱
        address: '', // 总部地址
        tags: [],
        // 权限组配置
        businessPkg: {
          packageId: '', // 权限组ID
          invalidTime: '', // 到期时间
          maxShopNum: '', // 最大店铺数
          noExpired: true // 是否无期限
        },
        // 商户更多信息
        businessInfo: {
          businessLicenseNum: null, // 营业执照号
          businessLicenseImg: null, // 营业执照片
          organizationCode: null, // 组织机构证号
          organizationCodeImg: null, // 组织机构证照片1
          organizationCodeImg2: null, // 组织机构证照片2
          legalPerson: null, // 法人姓名
          legalMobilePhone: null, // 法人手机号
          legalIdentityCard: null, // 法人身份证
          legalIdentityCardImg: null, // 法人身份证照片1
          legalIdentityCardImg2: null // 法人身份证照片2
        }
      },
	  form_disabled: false
    }
  },
  computed: {
    ...mapGetters(['fileBaseUrl', 'userInfo'])
  },
  watch: {},
  beforeCreate() {
  },
  created() {
  },
  beforeMount() {
  },
  mounted() {
    this.fetchPackageList()
    this.fetchTagOptions()
    this.fetchData()
  },
  beforeUpdate() {
  },
  update() {
  },
  activated() {
    this.fetchPackageList()
    this.fetchTagOptions()
  },
  deactivated() {
  },
  beforeDestroy() {
  },
  destroyed() {
  },
  methods: {
    /**
     * 数据组
     */
    // 初始化
    fetchData() {
	  // 设置修改权限
	  const source = this.userInfo.source
	  if (source == '0') {
        this.form_disabled = false
	  } else if (source == '1') {
        this.form_disabled = true
	  }

      if (this.$route.query.mchId) {
        this.businessId = this.$route.query.mchId
        this.mode = 'edit'
        this.fetchDetail()
      }
    },

    // 获取详情
    fetchDetail() {
      this.loading = true
      mchDetail({ params: { businessId: this.businessId } }).then(res => {
        if (!res.data.businessInfo) {
          res.data.businessInfo = {
            businessLicenseNum: null, // 营业执照号
            businessLicenseImg: null, // 营业执照片
            organizationCode: null, // 组织机构证号
            organizationCodeImg: null, // 组织机构证照片1
            organizationCodeImg2: null, // 组织机构证照片2
            legalPerson: null, // 法人姓名
            legalMobilePhone: null, // 法人手机号
            legalIdentityCard: null, // 法人身份证
            legalIdentityCardImg: null, // 法人身份证照片1
            legalIdentityCardImg2: null // 法人身份证照片2
          }
        }
        this.form = res.data
      }).finally(() => {
        this.loading = false
      })
    },

    // 获取权限组
    fetchPackageList() {
      const params = {
        pageNum: 1,
        pageSize: 99999
      }
      this.loading = true
      mchPackagePage({ data: params })
        .then((res) => {
          this.packageList = res.data.list
        })
        .finally(() => {
          this.loading = false
        })
    },

    // 获取标签
    fetchTagOptions() {
      tagList().then(res => {
        this.tagOptions = res.data || []
      }).finally(() => {
      })
    },

    /**
     * 按钮组
     */
    // 拦截图片上传
    uploadImgBefore(file, type) {
      switch (type) {
        case 'logoUrl':
          return this.$uploadImgBefore({ file, maxWidth: 300, maxHeight: 300, maxSizes: 0.5, fileType: ['JPG', 'PNG'] })
        default:
          return this.$uploadImgBefore({ file, maxSizes: 1, fileType: ['JPG', 'PNG'] })
      }
    },

    // 上传图片成功
    uploadImgSuccess(res, file, type) {
      if (res.code === 0) {
        switch (type) {
          case 'logoUrl':
            this.form.logoUrl = res.data.path
            this.$refs.form.clearValidate(['logoUrl'])
            break
          case 'businessLicenseImg':
            this.form.businessInfo.businessLicenseImg = res.data.path
            break
          case 'organizationCodeImg':
            this.form.businessInfo.organizationCodeImg = res.data.path
            break
          case 'legalIdentityCardImg':
            this.form.businessInfo.legalIdentityCardImg = res.data.path
            break
          case 'legalIdentityCardImg2':
            this.form.businessInfo.legalIdentityCardImg2 = res.data.path
            break
        }
      } else {
        this.$message.error(res.code + ' ' + res.msg)
      }
    },

    // 保存
    submitForm() {
      this.$refs.form.validate((valid, object) => {
        if (valid) {
          // 判断期限
          if (this.form.businessPkg.noExpired) this.form.businessPkg.invalidTime = ''
          const apiFun = this.mode === 'add' ? addMch : updateMch
          this.loading = true
          apiFun({ data: this.form }).then(res => {
            if (this.mode === 'add') {
              this.addMchInitData = res.data
              this.dialogVisible = true
            } else {
              this.$store.state.menus.activeSidebarMchInfo = Object.assign({}, this.form)
            }
            this.$notify({
              title: '成功',
              message: this.mode === 'add' ? '新增成功' : '更新成功',
              type: 'success',
              duration: 2000,
              offset: 40
            })
          }).finally(() => {
            this.loading = false
          })
        } else {
          Object.keys(object).some(v => {
            if (['businessInfo.legalPerson', 'businessInfo.legalMobilePhone', 'businessInfo.legalIdentityCard'].includes(v)) {
              this.isShowMoreConfig = true
              return true
            }
          })
        }
      })
    },

    // 复制剪切板
    handleCopyClipboard(text, event) {
      clip(text, event)
    },

    // 关闭弹框
    handleCloseDialog() {
      this.$emit('update:tabName', 'mchPage')
    }
    /**
     * 状态组
     */
    /**
     * 方法组
     */
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>

.mch-form-main {
  margin-top: 10px;

	.instructions {
		border: 1px solid #dcdfe6;
		padding: 16px;
		box-sizing: border-box;
		margin: 15px 0 50px;
		h3{
			margin: 0;
		}
	}

  .el-input,.el-textarea,.el-select{
    width: 500px;
  }
  .el-radio {
    line-height: 32px;
  }

  /*上传logo*/
  .upload-logo {
    .el-icon-plus {
      font-size: 32px;
      color: #8c939d;
      width: 100px;
      height: 100px;
      line-height: 100px;
      text-align: center;
    }

    .img {
      width: 100px;
      height: 100px;
      display: block;
    }
  }

  /* 上传证件 */
  .upload-card-tips {
    text-align: center;
  }

  .upload-card {
    .el-icon-plus {
      font-size: 32px;
      color: #8c939d;
      width: 300px;
      height: 180px;
      line-height: 180px;
      text-align: center;
    }

    .img {
      width: 300px;
      height: 180px;
      display: block;
    }
  }
}

</style>
